package com.zihan.evm;

import com.alibaba.fastjson.JSONObject;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 MrZihan
 * @version 创建时间：2021年10月14日
 * EntryHandler工厂<br>
 * 将各个实现类放入map
 */
@Configuration
@ConditionalOnBean(value = {EntryHandler.class})
public class HandlerFactory {

	private Map<String, EntryHandler> map = new HashMap<>();


	@Autowired
	private List<EntryHandler> entryHandlers;

	@PostConstruct
	public void init() {
		map = HandlerUtil.getTableHandlerMap(entryHandlers);
	}

	public EntryHandler getHandler(String tableName) {
		if (StringUtils.isBlank(tableName)) {
			return null;
		}
		return map.get(tableName);
	}

	public <R> R getModel(List<Map<String, String>> data, EntryHandler handler, int i){
		Class<R> tableClass = GenericUtil.getTableClass(handler);
		if (tableClass != null) {
			return JSONObject.parseObject(JSONObject.toJSONString(data.get(i)), tableClass);
		}
		return null;
	}
}